<template>
  <PageContainer>
    <Header title="" :default-slot-content-height="248">
      <template #title>
        <view class="hb-w-full hb-h-full hb-flex hb-items-center hb-justify-end hb-gap-3 hb-px-4">
          <TmButton
            v-if="
              data?.roleType === RoleTypeEnum.SUPER_ADMIN || data?.roleType === RoleTypeEnum.ADMIN
            "
            icon="ali-icon icon-shezhi1"
            :width="56"
            :round="10"
            :height="56"
            :fontSize="32"
            :margin="[0]"
            :shadow="0"
            :follow-theme="false"
            color="#EBEDF0"
            size="normal"
            @click="handleToCircleSetting"
          />
          <TmButton
            icon="ali-icon icon-share"
            :width="56"
            :round="10"
            :height="56"
            :fontSize="32"
            :margin="[0]"
            :shadow="0"
            :follow-theme="false"
            color="#EBEDF0"
            size="normal"
            @click="shareVisible = true"
          />
        </view>
      </template>
      <template>
        <view class="hb-p-4 hb-flex hb-items-center hb-box-content hb-h-12">
          <TmImage :src="data?.avatar" :width="96" :height="96" :round="4" error-img-type="unit" />
          <view class="hb-flex-1 hb-h-full hb-ml-3 hb-flex hb-flex-col hb-justify-around">
            <view class="hb-flex hb-items-center hb-justify-between">
              <TmText _class="hb-font-bold text-overflow-1" :label="data?.name" :font-size="36" />
              <TmButton
                v-if="!isJoin && data?.reviewStatus !== ReviewStatusEnum.PENDING"
                class="hb-flex-shrink-0"
                :margin="[0, 0]"
                :padding="[24, 0]"
                :block="true"
                :follow-theme="false"
                color="primary"
                font-color="primary"
                :height="48"
                :font-size="24"
                outlined
                :round="16"
                label="申请加入"
                @click="handleShowSelectAI"
              />
              <TmButton
                v-else-if="data?.reviewStatus === ReviewStatusEnum.PENDING && data.joinAuditEnabled"
                class="hb-flex-shrink-0"
                :margin="[0, 0]"
                :padding="[24, 0]"
                :block="true"
                :follow-theme="false"
                color="primary"
                font-color="primary"
                :height="48"
                :font-size="24"
                outlined
                :round="16"
                label="审核中"
              />
              <TmButton
                v-else-if="data?.roleType !== RoleTypeEnum.SUPER_ADMIN"
                class="hb-flex-shrink-0"
                :margin="[0, 0]"
                :padding="[24, 0]"
                :block="true"
                :follow-theme="false"
                color="#EA5E0E"
                font-color="#EA5E0E"
                :height="48"
                :font-size="24"
                outlined
                :round="16"
                label="退出"
                @click="handleQuit"
              />
            </view>
            <view v-if="data?.certificationName" class="hb-flex hb-items-center">
              <TmIcon
                _class="hb-mr-1"
                name="ali-icon icon-Frame1"
                color="#5396FF"
                :font-size="32"
              />
              <TmText :label="data?.certificationName" color="primary" :font-size="24" />
            </view>
          </view>
        </view>
        <TmTabs
          v-model:active-name="activeTab"
          :list="tabsList"
          :item-width="itemWidth"
          :width="windowWidth"
          :default-name="activeTab"
          transparent
          :item-font-size="28"
          tabs-line-ani-color="primary"
          active-font-color="#333"
          un-selected-color="#969799"
          show-tabs-line-ani
          :show-tabs-line="false"
          :tabs-line-width="60"
        ></TmTabs>
      </template>
    </Header>
    <view>
      <!-- 简介 -->
      <view
        v-if="activeTab === 0"
        class="hb-m-4 hb-px-4 hb-py-3 hb-bg-white hb-box-shadow-base hb-rounded-xl"
      >
        <TmText _class="hb-mb-2 hb-font-bold" label="圈子简介" :font-size="28" />
        <TmText
          v-if="data?.description"
          :label="data?.description"
          :font-size="28"
          color="#646566"
          :line-height="40"
        />

        <Empty v-else text="暂无圈子简介" />
      </view>
      <!-- 成员列表 -->
      <MemberList
        ref="memberListRef"
        v-if="activeTab === 1 && data"
        :id="data!.id"
        :role-type="data!.roleType"
        :update-member-num="updateMemberNum"
      />
      <!-- 文件列表 -->
      <FileList
        ref="fileListRef"
        v-if="activeTab === 2 && data"
        :id="data!.id"
        :role-type="data!.roleType"
        :update-file-num="updateFileNum"
      />
      <!-- 申请加入的状态 -->
      <!-- <ApplyStatusView v-if="!isJoin && data" :review-status="data?.reviewStatus" /> -->
      <template v-if="isJoin && data">
        <view class="hb-w-full hb-h-17"></view>
        <view class="hb-w-full hb-p-6 hb-fixed hb-left-0 hb-bottom-19">
          <ChatInput
            placeholder="基于圈子知识库提问…"
            disabled
            :circle-uuid="data?.uuid"
            :circle-name="data?.name"
          />
        </view>
        <!-- 底部操作按钮 -->
        <BottomSubmit
          :hide-cancel-btn="!data.fileUploadPerm"
          cancel-btn-label="添加共享文件"
          submit-btn-label="邀请成员"
          submit-btn-open-type="share"
          @cancel="handleAddCircleSharedFile"
        />
      </template>

      <SelectAI
        v-if="data"
        v-model="showSelectAI"
        modal-title="确定要用以下智能助手加入？"
        modal-ok-text="申请加入"
        @ok="handleApplyJoin"
      />
      <CustomShare
        v-model="shareVisible"
        :is-custom-wx-share-callback="true"
        :show-copy-link="true"
        :code-url="data?.qrCodeUrl"
      />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* circleDetail 圈子详情 */
  // import ApplyStatusView from './components/ApplyStatusView.vue';
  import MemberList from './components/MemberList.vue';
  import FileList from './components/FileList.vue';
  import { getUrl } from '@/router';
  import { appBotCircleDetail, applyJoinCircle, exitCircle } from '@/api/contact';
  import { CircleDetailResult } from '@/api/contact/types';
  import { RoleTypeEnum } from '@/enums/LoginEnum';
  import { useUserStore } from '@/store/modules/user';
  import { Toast, updateCounter } from '@/utils';
  import { TabbarPageEnum } from '@/enums/PageEnum';
  import { ReviewStatusEnum, WxShareButtonIdEnum } from '@/enums/PublicEnum';
  import { isCreatedAI } from '@/utils/is';
  import { AiAccountBotListResult } from '@/api/aiSettings/types';
  import { CircleDetail } from '@/router/types/modules';

  const shareVisible = ref(false);

  const memberTabTitle = (num: number) => `成员(${num || 0})`;
  const fileTabTitle = (num: number) => `知识库(${num || 0})`;

  // 当前激活的标签页
  const activeTab = ref(0);
  const tabsList = ref<Tmui.tabs[]>([
    { key: 0, title: '简介' },
    { key: 1, title: memberTabTitle(0), disabled: true },
    { key: 2, title: fileTabTitle(0), disabled: true },
  ]);

  const isJoin = ref(false);

  const data = ref<CircleDetailResult>();
  const memberListRef = ref<InstanceType<typeof MemberList>>();
  const fileListRef = ref<InstanceType<typeof FileList>>();

  const memberRefresh = () => activeTab.value === 1 && memberListRef.value?.refresh();

  /** 更新成员数量 */
  const updateMemberNum = (type: 'add' | 'subtract', num: number) => {
    const memberNum = data.value!.memberNum;
    data.value!.memberNum = updateCounter(memberNum, num, type);
    tabsList.value[1].title = memberTabTitle(data.value!.memberNum);
  };

  /** 更新文件数量 */
  const updateFileNum = (type: 'add' | 'subtract', num: number = 1) => {
    const fileNum = data.value!.fileNum;
    data.value!.fileNum = updateCounter(fileNum, num, type);
    tabsList.value[2].title = fileTabTitle(data.value!.fileNum);
  };
  const fileRefresh = () => activeTab.value === 2 && fileListRef.value?.refresh();

  const getData = async (uuid: string = data.value!.uuid) => {
    const res = await appBotCircleDetail({ uuid });
    data.value = res;
    isJoin.value = !!res.join;
    tabsList.value[1].title = memberTabTitle(res.memberNum);
    tabsList.value[2].title = fileTabTitle(res.fileNum);

    /** 未加入当前出圈子 */
    if (!isJoin.value) {
      tabsList.value[1].disabled = true;
      tabsList.value[1].suffixIcon = 'ali-icon icon-suo';
      tabsList.value[2].disabled = true;
      tabsList.value[2].suffixIcon = 'ali-icon icon-suo';
    } else {
      tabsList.value[1].disabled = false;
      tabsList.value[1].suffixIcon = '';
      tabsList.value[2].disabled = false;
      tabsList.value[2].suffixIcon = '';
    }
  };

  let success: CircleDetail['success'];
  customOnload<'circleDetail'>(async (op) => {
    getData(op.uuid);
    success = op.success;
  });

  const windowWidth = computed(() => {
    const w = uni.getWindowInfo().windowWidth;
    return w / (uni.upx2px(100) / 100);
  });

  const itemWidth = computed(() => {
    return windowWidth.value / tabsList.value.length;
  });

  const handleToCircleSetting = () => {
    navigateTo({
      name: 'circleSetting',
      options: {
        uuid: data.value!.uuid,
        success: (type) => {
          if (type === 'baseInfo') {
            success?.();
            getData();
          }
          if (type === 'memberList') memberRefresh();
        },
      },
    });
  };

  const showSelectAI = ref(false);
  const handleShowSelectAI = () => {
    isCreatedAI(() => {
      showSelectAI.value = true;
    });
  };

  /** 申请加入圈子 */
  const handleApplyJoin = (item: AiAccountBotListResult) => {
    isCreatedAI(() => {
      applyJoinCircle({ circleId: data.value!.id, botId: item.id }).then(() => {
        handleApplyJoinSuccess();
      });
    });
  };

  function handleApplyJoinSuccess() {
    showSelectAI.value = false;
    const content = data.value!.joinAuditEnabled
      ? '本圈子需要管理员同意后才可加入，请耐心等待管理员审核。'
      : '您已成功加入！';
    uni.showModal({
      title: data.value!.joinAuditEnabled ? '加入申请已送达' : '提示',
      content,
      confirmText: '确定',
      showCancel: false,
      confirmColor: '#2878FF',
    });
    getData();
  }

  const handleQuit = () => {
    uni.showModal({
      title: '退出圈子',
      content:
        '确定要退出圈子吗？退出后将无法再使用圈子知识库匹配圈子资源，你共享的文件将从知识库移除。',
      confirmText: '确认退出',
      cancelColor: '#999996',
      cancelText: '取消',
      confirmColor: '#EA5E0E',
      success: async (res) => {
        if (res.confirm) {
          await exitCircle({ id: data.value!.id });
          useUserStore().getUserInfo();
          Toast({
            title: '操作成功',
            success: () => switchTab(TabbarPageEnum.BASE_HOME),
          });
        }
      },
    });
  };

  const handleAddCircleSharedFile = () => {
    navigateTo({
      name: 'addCircleSharedFile',
      options: {
        circleId: data.value!.id,
        success: (num) => {
          updateFileNum('add', num);
          fileRefresh();
        },
      },
    });
  };

  onShareAppMessage((e) => {
    console.log(e);

    const title =
      e.target?.id === WxShareButtonIdEnum.BottomSubmit
        ? `邀请你加入"${data.value!.name}"`
        : '给你分享一个优质圈子，快来看看吧';
    return {
      title,
      path: getUrl('circleDetail', { uuid: data.value!.uuid }),
      imageUrl: 'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/saas-ai/share-img.png',
    };
  });
</script>

<style lang="scss" scoped></style>
